package com.rookie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rookie.common.lang.Result;
import com.rookie.entity.Role;
import com.rookie.entity.RoleMenu;
import com.rookie.entity.UserRole;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 前端控制器
 */
@RestController
@RequestMapping("/rookie/role")
public class RoleController extends BaseController {

    /**
     * 新增
     */
    @PostMapping("save")
    @PreAuthorize("hasAuthority('sys:role:save')")
    public Result save(@Validated @RequestBody Role role) {
        role.setCreateTime(LocalDateTime.now());
        roleService.save(role);
        return Result.success(role);
    }

    /**
     * 分页列表
     */
    @GetMapping("list")
    @PreAuthorize("hasAuthority('sys:role:list')")
    public Result list(String name) {
        Page<Role> page = roleService.page(getPage(), new LambdaQueryWrapper<Role>().like(StringUtils.isNotBlank(name), Role::getName, name));
        return Result.success(page);
    }

    /**
     * 根据id查询角色信息
     */
    @GetMapping("getInfoById/{id}")
    @PreAuthorize("hasAuthority('sys:role:list')")
    public Result getInfoById(@PathVariable Long id) {
        Role role = roleService.getById(id);
        List<RoleMenu> roleMenuList = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, id));
        List<Long> menuIdsList = roleMenuList.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        role.setMenuIdsList(menuIdsList);
        return Result.success(role);
    }

    /**
     * 修改
     */
    @PostMapping("update")
    @PreAuthorize("hasAuthority('sys:role:update')")
    public Result update(@Validated @RequestBody Role role) {
        role.setUpdateTime(LocalDateTime.now());
        roleService.updateById(role);
        userService.clearRedisAuthorityByRole(role.getId());
        return Result.success(role);
    }

    /**
     * 删除
     */
    @PostMapping("delete")
    @PreAuthorize("hasAuthority('sys:role:delete')")
    @Transactional(rollbackFor = Exception.class)
    public Result delete(@RequestBody Long[] ids) {
        roleService.removeByIds(Arrays.asList(ids));
        // 删除角色菜单中间表
        roleMenuService.remove(new LambdaQueryWrapper<RoleMenu>().in(RoleMenu::getRoleId, Arrays.asList(ids)));
        // 删除用户角色中间表
        userRoleService.remove(new LambdaQueryWrapper<UserRole>().in(UserRole::getRoleId, Arrays.asList(ids)));
        // 清空Redis缓存
        Arrays.stream(ids).forEach(id -> userService.clearRedisAuthorityByRole(id));
        return Result.success("");
    }

    /**
     * 分配权限
     */
    @PostMapping("AssignPermissions/{roleId}")
    @PreAuthorize("hasAuthority('sys:role:perm')")
    @Transactional(rollbackFor = Exception.class)
    public Result AssignPermissions(@PathVariable Long roleId, @RequestBody Long[] menuIds) {
        // 先删除原来角色和菜单的关系
        roleMenuService.remove(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId));
        List<RoleMenu> roleMenusList = new ArrayList<>();
        Arrays.stream(menuIds).forEach(menuId -> {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(roleId);
            roleMenusList.add(roleMenu);
        });
        roleMenuService.saveBatch(roleMenusList);
        // 清除Redis中的缓存
        userService.clearRedisAuthorityByRole(roleId);
        return Result.success("");
    }

}
